package com.zmyuan.demo.netty.thrift.socket;

import com.zmyuan.demo.netty.thrift.Content;
import com.zmyuan.demo.netty.thrift.Msg;
import com.zmyuan.demo.netty.thrift.ThriftRequest;
import com.zmyuan.demo.netty.thrift.service.ThriftService;
import com.zmyuan.demo.netty.thrift.utils.ThriftUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TMemoryBuffer;
import org.apache.thrift.transport.TTransport;

import java.lang.reflect.Method;
import java.nio.charset.Charset;

/**
 * Created by zdb on 2017/2/15.
 */
public class ThriftServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // ByteBuf 转换成一个 ThriftRequest
        ByteBuf buf = (ByteBuf)msg;
        byte[] dst = null;
        if(buf.hasArray()) {
            dst = buf.array();
        } else {
            dst = new byte[buf.readableBytes()];
            buf.readBytes(dst);
        }

        ThriftRequest req = ThriftUtils.convertBytesToObject(dst, ThriftRequest.class);

        String cmd = req.getCommand();
        if(cmd.equals("saveMsg")) {
            new ThriftService().saveMsg(ThriftUtils.convertBytesToObject(req.getRequestParam(), Msg.class));
        } else if("saveContent".equals(cmd)) {
            Content content = new ThriftService().saveContent(ThriftUtils.convertBytesToObject(req.getRequestParam(), Content.class));
            ctx.writeAndFlush(content);
        }

    }
}
